package com.ly.thread;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Shop2 {
    private static int number = 0;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public void create() {
        lock.lock();
        try{
            while(number>=2) {
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName()+" "+number);
            condition.signalAll();
        }catch (Exception e) {

        }finally {
            lock.unlock();
        }
    }

    public void sell() {
        lock.lock();
        try{
            while(number<2) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+" "+number);
            condition.signalAll();
        }catch (Exception e) {

        }finally {
            lock.unlock();
        }
    }
}


public class ThreadCondition {
    public static void main(String[] args) {
        Shop2 shop2 = new Shop2();
        for(int i=0;i<4;i++) {
            new Thread(() -> {shop2.create();},"A").start();
            new Thread(() -> {shop2.create();},"B").start();
            new Thread(() -> {shop2.sell();},"C").start();
        }

    }
}
